package com.xyh.flowershop.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyh.flowershop.domain.Swipers;
import com.xyh.flowershop.mapper.SwipersMapper;
import com.xyh.flowershop.service.SwipersService;
import com.xyh.flowershop.vo.req.swiper.SwiperEditReqVo;
import com.xyh.flowershop.vo.req.swiper.SwiperPageReqVo;
import com.xyh.flowershop.vo.resp.index.SwiperRespVo;
import com.xyh.flowershop.vo.resp.swiper.SwiperPageRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author 小约翰可汗
 * @className SwipersServiceImpl
 * @createTime 2024/3/3120:43
 */
@Service
public class SwipersServiceImpl extends ServiceImpl<SwipersMapper, Swipers> implements SwipersService {
    @Override
    public List<SwiperRespVo> getSwiperList() {

        return baseMapper.selectSwiperList();
    }

    @Override
    @Transactional
    public Boolean addSwiper(SwiperEditReqVo vo) {
        LambdaQueryWrapper<Swipers> swiperWrapper = new LambdaQueryWrapper<>();
        swiperWrapper.eq(Swipers::getGoodId, vo.getGoodId())
                .eq(Swipers::getDeleted, false);
        // 判断该商品是否已经绑定轮播图
        Swipers swipers = baseMapper.selectOne(swiperWrapper);
        if(Objects.isNull(swipers)){
            swipers = new Swipers();
            BeanUtils.copyProperties(vo, swipers);
            return baseMapper.insert(swipers) > 0;
        }
        swipers.setSwiperImgUrl(vo.getSwiperImgUrl());
        return baseMapper.updateById(swipers) > 0;

    }

    @Override
    public Boolean editSwiper(SwiperEditReqVo vo) {
        Swipers swipers = baseMapper.selectById(vo.getId());
        BeanUtils.copyProperties(vo, swipers);
        return baseMapper.updateById(swipers) > 0;
    }

    @Override
    public Boolean deleteSwiper(List<Long> ids) {
        return baseMapper.deleteSwiper(ids) > 0;
    }

    @Override
    public IPage<SwiperPageRespVo> getPageSwiper(SwiperPageReqVo vo) {
        IPage<SwiperPageRespVo> pages = new Page<>(vo.getPageIndex(), vo.getPageSize());
        pages = baseMapper.selectSwiperPage(pages, vo);
        return pages;
    }

    @Override
    public SwiperPageRespVo getSwiper(Long id) {
        SwiperPageReqVo vo = new SwiperPageReqVo();
        vo.setPageIndex(1L);
        vo.setPageSize(10L);
        vo.setId(id.toString());
        List<SwiperPageRespVo> records = this.getPageSwiper(vo).getRecords();
        return records.size() > 0 ? records.get(0) : new SwiperPageRespVo();
    }

    @Override
    public Boolean changeStatus(Long id, Integer status) {
        return baseMapper.changeStatus(id, status) > 0;
    }
}
